/**
 * Optimizer Store
 * 管理全文优化、SEO分析、可读性分析的状态
 */

import { create } from 'zustand';
import { persist } from 'zustand/middleware';

/**
 * 优化类型
 */
export type OptimizationType = 'seo' | 'readability' | 'professional' | 'balanced';

/**
 * 问题严重程度
 */
export type IssueSeverity = 'critical' | 'high' | 'medium' | 'low';

/**
 * 优化建议接口
 */
export interface OptimizationSuggestion {
  id: string;
  type: 'title' | 'opening' | 'structure' | 'redundancy' | 'missing' | 'language' | 'seo';
  severity: IssueSeverity;
  title: string;
  description: string;
  position?: number;
  originalText?: string;
  suggestedText?: string;
  impact: string;          // 影响描述
  effort: 'low' | 'medium' | 'high';  // 实施难度
  timestamp: number;
}

/**
 * 问题接口
 */
export interface Issue {
  id: string;
  type: 'logic' | 'grammar' | 'redundancy' | 'missing_info' | 'readability';
  severity: IssueSeverity;
  position: number;
  length: number;
  description: string;
  suggestion: string;
}

/**
 * 质量报告
 */
export interface QualityReport {
  overallScore: number;           // 综合评分 0-100
  structureScore: number;         // 结构评分
  coherenceScore: number;         // 连贯性评分
  readabilityScore: number;       // 可读性评分
  originalityScore: number;       // 原创度评分
  seoScore: number;               // SEO评分
  languageScore: number;          // 语言质量评分

  strengths: string[];            // 优点
  weaknesses: string[];           // 缺点
  suggestions: OptimizationSuggestion[];
  issues: Issue[];

  analyzedAt: number;
}

/**
 * 关键词信息
 */
export interface Keyword {
  word: string;
  count: number;
  density: number;            // 密度 百分比
  positions: number[];        // 出现位置
  importance: 'primary' | 'secondary' | 'tertiary';
}

/**
 * SEO分析结果
 */
export interface SEOAnalysis {
  keywords: Keyword[];
  titleScore: number;                    // 标题SEO评分 0-100
  titleLength: number;                   // 标题长度
  titleSuggestion?: string;              // 标题优化建议

  metaDescription?: string;              // Meta描述
  metaDescriptionScore: number;          // Meta描述评分

  headingStructure: Array<{
    level: 'H1' | 'H2' | 'H3' | 'H4' | 'H5' | 'H6';
    text: string;
    position: number;
  }>;

  internalLinks: number;                 // 内部链接数
  externalLinks: number;                 // 外部链接数
  imageCount: number;                    // 图片数
  imagesWithAlt: number;                 // 有Alt文本的图片数

  keywordDistribution: {                 // 关键词分布
    title: number;
    firstParagraph: number;
    body: number;
    lastParagraph: number;
  };

  recommendations: string[];             // SEO建议
  competitorKeywords: string[];          // 竞争关键词
  longTailKeywords: string[];            // 长尾关键词建议
}

/**
 * 可读性分析
 */
export interface ReadabilityAnalysis {
  readingLevel: number;                  // 阅读难度 1-10级
  avgSentenceLength: number;             // 平均句子长度
  avgParagraphLength: number;            // 平均段落长度
  complexWords: Array<{
    word: string;
    position: number;
    simpler: string[];                  // 更简单的替代词
  }>;
  passiveVoiceCount: number;             // 被动语态数量
  transitionWords: number;               // 过渡词数量

  sentenceLengthDistribution: {
    short: number;      // < 15 words
    medium: number;     // 15-25 words
    long: number;       // > 25 words
  };

  fleschScore: number;                   // Flesch可读性评分
  targetAudience: 'general' | 'professional' | 'expert';
  improvements: string[];
}

/**
 * 优化版本
 */
export interface OptimizedVersion {
  id: string;
  type: OptimizationType;
  title: string;
  content: string;
  score: number;
  changes: Array<{
    type: string;
    description: string;
    position: number;
  }>;
  createdAt: number;
}

/**
 * 对比数据
 */
export interface ComparisonData {
  original: {
    score: number;
    wordCount: number;
    readabilityScore: number;
    seoScore: number;
  };
  optimized: {
    score: number;
    wordCount: number;
    readabilityScore: number;
    seoScore: number;
  };
  improvements: string[];
  degradations: string[];
}

export interface OptimizerState {
  // 分析状态
  isAnalyzing: boolean;
  isOptimizing: boolean;

  // 原文内容
  originalContent: string;

  // 分析结果
  qualityReport: QualityReport | null;
  seoAnalysis: SEOAnalysis | null;
  readabilityAnalysis: ReadabilityAnalysis | null;

  // 优化版本
  optimizedVersions: OptimizedVersion[];
  selectedVersionId: string | null;

  // 对比数据
  comparisonData: ComparisonData | null;

  // 优化历史
  optimizationHistory: Array<{
    timestamp: number;
    type: OptimizationType;
    score: number;
  }>;

  // Actions
  setOriginalContent: (content: string) => void;

  analyzeArticle: (content: string) => Promise<void>;
  analyzeSEO: (content: string) => Promise<void>;
  analyzeReadability: (content: string) => Promise<void>;
  analyzeAll: (content: string) => Promise<void>;

  optimizeArticle: (type: OptimizationType) => Promise<void>;
  applySuggestion: (suggestionId: string) => Promise<void>;
  applyAllSuggestions: () => Promise<void>;

  generateOptimizedVersions: () => Promise<void>;
  selectVersion: (versionId: string) => void;
  compareVersions: (originalContent: string, optimizedContent: string) => Promise<void>;

  exportReport: () => Promise<Blob>;

  clearAll: () => void;
}

export const useOptimizerStore = create<OptimizerState>()(
  persist(
    (set, get) => ({
      isAnalyzing: false,
      isOptimizing: false,

      originalContent: '',

      qualityReport: null,
      seoAnalysis: null,
      readabilityAnalysis: null,

      optimizedVersions: [],
      selectedVersionId: null,

      comparisonData: null,

      optimizationHistory: [],

      /**
       * 设置原文内容
       */
      setOriginalContent: (content) => {
        set({ originalContent: content });
      },

      /**
       * 分析文章质量
       */
      analyzeArticle: async (content) => {
        console.log('📊 [Optimizer] Analyzing article quality...');

        set({ isAnalyzing: true });

        try {
          // TODO: 调用API分析
          // const response = await articleOptimizerService.analyzeArticle(content);

          // Mock质量报告
          const mockReport = get().generateMockQualityReport(content);

          set({
            qualityReport: mockReport,
            isAnalyzing: false,
          });

          console.log('✅ [Optimizer] Analysis complete, score:', mockReport.overallScore);
        } catch (error) {
          console.error('❌ [Optimizer] Analysis failed:', error);
          set({ isAnalyzing: false });
        }
      },

      /**
       * 分析SEO
       */
      analyzeSEO: async (content) => {
        console.log('🔍 [Optimizer] Analyzing SEO...');

        try {
          // TODO: 调用API分析
          // const response = await seoAnalyzerService.analyzeSEO(content);

          // Mock SEO分析
          const mockSEO = get().generateMockSEOAnalysis(content);

          set({ seoAnalysis: mockSEO });

          console.log('✅ [Optimizer] SEO analysis complete');
        } catch (error) {
          console.error('❌ [Optimizer] SEO analysis failed:', error);
        }
      },

      /**
       * 分析可读性
       */
      analyzeReadability: async (content) => {
        console.log('📖 [Optimizer] Analyzing readability...');

        try {
          // TODO: 调用API分析
          // const response = await readabilityService.analyze(content);

          // Mock可读性分析
          const mockReadability = get().generateMockReadabilityAnalysis(content);

          set({ readabilityAnalysis: mockReadability });

          console.log('✅ [Optimizer] Readability analysis complete');
        } catch (error) {
          console.error('❌ [Optimizer] Readability analysis failed:', error);
        }
      },

      /**
       * 全面分析
       */
      analyzeAll: async (content) => {
        console.log('🚀 [Optimizer] Starting comprehensive analysis...');

        set({ isAnalyzing: true, originalContent: content });

        try {
          await Promise.all([
            get().analyzeArticle(content),
            get().analyzeSEO(content),
            get().analyzeReadability(content),
          ]);

          console.log('✅ [Optimizer] All analyses complete');
        } catch (error) {
          console.error('❌ [Optimizer] Analysis failed:', error);
        } finally {
          set({ isAnalyzing: false });
        }
      },

      /**
       * 优化文章
       */
      optimizeArticle: async (type) => {
        console.log('✨ [Optimizer] Optimizing article, type:', type);

        set({ isOptimizing: true });

        try {
          const { originalContent } = get();

          // TODO: 调用API优化
          // const response = await articleOptimizerService.optimizeArticle(originalContent, { optimizationType: type });

          // Mock优化结果
          const optimized = get().generateMockOptimizedContent(originalContent, type);

          const newVersion: OptimizedVersion = {
            id: `v_${Date.now()}`,
            type,
            title: `${type}优化版本`,
            content: optimized,
            score: 85 + Math.random() * 10,
            changes: [],
            createdAt: Date.now(),
          };

          set((state) => ({
            optimizedVersions: [...state.optimizedVersions, newVersion],
            selectedVersionId: newVersion.id,
            isOptimizing: false,
            optimizationHistory: [
              ...state.optimizationHistory,
              {
                timestamp: Date.now(),
                type,
                score: newVersion.score,
              },
            ],
          }));

          console.log('✅ [Optimizer] Optimization complete');
        } catch (error) {
          console.error('❌ [Optimizer] Optimization failed:', error);
          set({ isOptimizing: false });
        }
      },

      /**
       * 应用单个建议
       */
      applySuggestion: async (suggestionId) => {
        console.log('🔧 [Optimizer] Applying suggestion:', suggestionId);

        const { qualityReport } = get();
        if (!qualityReport) return;

        const suggestion = qualityReport.suggestions.find((s) => s.id === suggestionId);
        if (!suggestion || !suggestion.suggestedText) return;

        // TODO: 应用建议到文章内容
        console.log('✅ [Optimizer] Suggestion applied');
      },

      /**
       * 应用所有建议
       */
      applyAllSuggestions: async () => {
        console.log('🔧 [Optimizer] Applying all suggestions...');

        const { qualityReport } = get();
        if (!qualityReport) return;

        for (const suggestion of qualityReport.suggestions) {
          await get().applySuggestion(suggestion.id);
        }

        console.log('✅ [Optimizer] All suggestions applied');
      },

      /**
       * 生成多个优化版本
       */
      generateOptimizedVersions: async () => {
        console.log('🎨 [Optimizer] Generating optimized versions...');

        set({ isOptimizing: true });

        try {
          await Promise.all([
            get().optimizeArticle('seo'),
            get().optimizeArticle('readability'),
            get().optimizeArticle('professional'),
          ]);

          console.log('✅ [Optimizer] All versions generated');
        } catch (error) {
          console.error('❌ [Optimizer] Version generation failed:', error);
        } finally {
          set({ isOptimizing: false });
        }
      },

      /**
       * 选择版本
       */
      selectVersion: (versionId) => {
        set({ selectedVersionId: versionId });
      },

      /**
       * 对比版本
       */
      compareVersions: async (originalContent, optimizedContent) => {
        console.log('📊 [Optimizer] Comparing versions...');

        // TODO: 调用API进行对比分析
        // const response = await comparisonService.compare(originalContent, optimizedContent);

        // Mock对比数据
        const mockComparison: ComparisonData = {
          original: {
            score: 72,
            wordCount: originalContent.length,
            readabilityScore: 65,
            seoScore: 58,
          },
          optimized: {
            score: 88,
            wordCount: optimizedContent.length,
            readabilityScore: 82,
            seoScore: 76,
          },
          improvements: [
            '整体评分提升16分',
            '可读性提升17分',
            'SEO评分提升18分',
            '添加了5个关键词',
            '优化了标题结构',
          ],
          degradations: [],
        };

        set({ comparisonData: mockComparison });

        console.log('✅ [Optimizer] Comparison complete');
      },

      /**
       * 导出报告
       */
      exportReport: async (): Promise<Blob> => {
        console.log('📄 [Optimizer] Exporting report...');

        const { qualityReport, seoAnalysis, readabilityAnalysis } = get();

        // TODO: 生成PDF报告
        // const pdf = await reportGenerator.generate({ qualityReport, seoAnalysis, readabilityAnalysis });

        // Mock PDF数据
        const mockPDF = new Blob(['Mock PDF content'], { type: 'application/pdf' });

        console.log('✅ [Optimizer] Report exported');
        return mockPDF;
      },

      /**
       * 清空所有数据
       */
      clearAll: () => {
        set({
          originalContent: '',
          qualityReport: null,
          seoAnalysis: null,
          readabilityAnalysis: null,
          optimizedVersions: [],
          selectedVersionId: null,
          comparisonData: null,
        });
      },

      /**
       * 生成Mock质量报告
       */
      generateMockQualityReport: (content: string): QualityReport => {
        const wordCount = content.length;
        const hasGoodStructure = content.includes('\n\n');
        const hasHeadings = content.includes('#') || content.includes('##');

        return {
          overallScore: 75 + Math.floor(Math.random() * 15),
          structureScore: hasGoodStructure ? 85 : 70,
          coherenceScore: 78,
          readabilityScore: wordCount > 500 ? 72 : 80,
          originalityScore: 92,
          seoScore: hasHeadings ? 68 : 55,
          languageScore: 82,

          strengths: [
            '文章结构清晰，层次分明',
            '语言表达流畅，易于理解',
            '内容原创性高',
          ],

          weaknesses: [
            'SEO关键词布局需要优化',
            '部分段落过长，影响阅读体验',
            '缺少数据支撑',
          ],

          suggestions: [
            {
              id: 'sug_1',
              type: 'title',
              severity: 'high',
              title: '优化标题以提升吸引力',
              description: '当前标题过于简单，建议添加关键词并突出价值主张',
              impact: '预计可提升点击率15-20%',
              effort: 'low',
              timestamp: Date.now(),
            },
            {
              id: 'sug_2',
              type: 'opening',
              severity: 'medium',
              title: '改进开头以吸引读者',
              description: '建议在开头添加引人入胜的故事或数据，快速抓住读者注意力',
              impact: '预计可降低跳出率10%',
              effort: 'medium',
              timestamp: Date.now(),
            },
            {
              id: 'sug_3',
              type: 'structure',
              severity: 'medium',
              title: '优化段落结构',
              description: '部分段落超过150字，建议拆分为2-3个小段落',
              impact: '提升可读性评分8-10分',
              effort: 'low',
              timestamp: Date.now(),
            },
            {
              id: 'sug_4',
              type: 'seo',
              severity: 'high',
              title: '增加目标关键词',
              description: '建议在标题、首段和正文中增加核心关键词的出现频率',
              impact: '预计SEO评分提升15-20分',
              effort: 'medium',
              timestamp: Date.now(),
            },
          ],

          issues: [
            {
              id: 'issue_1',
              type: 'redundancy',
              severity: 'low',
              position: 150,
              length: 50,
              description: '此处内容重复',
              suggestion: '删除重复表述，保持简洁',
            },
          ],

          analyzedAt: Date.now(),
        };
      },

      /**
       * 生成Mock SEO分析
       */
      generateMockSEOAnalysis: (content: string): SEOAnalysis => {
        return {
          keywords: [
            { word: 'AI写作', count: 8, density: 2.1, positions: [10, 50, 120, 200, 300, 400, 500, 600], importance: 'primary' },
            { word: '内容创作', count: 6, density: 1.6, positions: [30, 100, 250, 350, 450, 550], importance: 'primary' },
            { word: '优化', count: 5, density: 1.3, positions: [80, 180, 280, 380, 480], importance: 'secondary' },
            { word: '效率', count: 4, density: 1.0, positions: [150, 250, 350, 450], importance: 'secondary' },
            { word: '技术', count: 3, density: 0.8, positions: [200, 300, 400], importance: 'tertiary' },
          ],

          titleScore: 65,
          titleLength: content.split('\n')[0]?.length || 0,
          titleSuggestion: '建议标题长度控制在50-60字符，并包含核心关键词',

          metaDescription: '本文探讨AI写作技术如何提升内容创作效率...',
          metaDescriptionScore: 70,

          headingStructure: [
            { level: 'H1', text: '主标题', position: 0 },
            { level: 'H2', text: '第一部分', position: 100 },
            { level: 'H2', text: '第二部分', position: 300 },
            { level: 'H3', text: '子章节', position: 350 },
          ],

          internalLinks: 2,
          externalLinks: 3,
          imageCount: 1,
          imagesWithAlt: 0,

          keywordDistribution: {
            title: 1,
            firstParagraph: 2,
            body: 8,
            lastParagraph: 1,
          },

          recommendations: [
            '标题中添加核心关键词"AI写作"',
            '首段关键词密度较低，建议增加到2-3%',
            '添加更多内部链接，建议5-8个',
            '为图片添加Alt文本，提升SEO',
            '优化Meta描述，包含核心关键词',
            '建议添加H2、H3标签优化结构',
          ],

          competitorKeywords: [
            '智能写作',
            'AI文章生成',
            '自动化创作',
            '写作助手',
          ],

          longTailKeywords: [
            'AI写作工具如何提升效率',
            '内容创作AI技术应用',
            '智能写作平台推荐',
          ],
        };
      },

      /**
       * 生成Mock可读性分析
       */
      generateMockReadabilityAnalysis: (content: string): ReadabilityAnalysis => {
        const sentences = content.split(/[。！？.!?]/).filter(s => s.trim().length > 0);
        const paragraphs = content.split(/\n\n+/).filter(p => p.trim().length > 0);

        return {
          readingLevel: 6,
          avgSentenceLength: 18.5,
          avgParagraphLength: 120,

          complexWords: [
            { word: '革命性', position: 150, simpler: ['重大', '巨大'] },
            { word: '范式', position: 300, simpler: ['模式', '方式'] },
            { word: '赋能', position: 450, simpler: ['帮助', '提升'] },
          ],

          passiveVoiceCount: 3,
          transitionWords: 8,

          sentenceLengthDistribution: {
            short: Math.floor(sentences.length * 0.3),
            medium: Math.floor(sentences.length * 0.5),
            long: Math.floor(sentences.length * 0.2),
          },

          fleschScore: 62,
          targetAudience: 'general',

          improvements: [
            '减少被动语态的使用，改为主动语态',
            '将长句子拆分为2-3个短句',
            '用更简单的词汇替换复杂词汇',
            '增加过渡词的使用，提升连贯性',
            '控制段落长度在100字以内',
          ],
        };
      },

      /**
       * 生成Mock优化内容
       */
      generateMockOptimizedContent: (content: string, type: OptimizationType): string => {
        const prefix = type === 'seo' ? '[SEO优化] ' :
                      type === 'readability' ? '[可读性优化] ' :
                      type === 'professional' ? '[专业深度优化] ' : '[平衡优化] ';

        return prefix + content + '\n\n【优化说明】：本版本已根据' + type + '策略进行优化。';
      },
    }),
    {
      name: 'optimizer-storage',
      partialize: (state) => ({
        optimizationHistory: state.optimizationHistory,
      }),
    }
  )
);
